// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"

class FToolBarBuilder;
class FMenuBuilder;

struct FScriptPathItem
{
	FScriptPathItem(const FString& InPath): mPath{InPath}
	{
		// 如果是一个目录
		if(FPaths::DirectoryExists(mPath))
		{
			bIsFolder = true;
		}
		else
		{
			bIsFolder = false;
		}

		mName = FPaths::GetBaseFilename(mPath);
		mAlias = mName;
	};
	
	// 路径
	FString mPath;
	// 文件/文件夹名
	FString mName;
	// 别名
	FString mAlias;
	// 是否是文件夹
	bool bIsFolder;
	// 层级（最顶层是 0 级）
	int8_t mLevel = 0;
	// 子元素
	TArray<TSharedPtr<FScriptPathItem>> mChildren;
};

class FPyShelfModule : public IModuleInterface
{
public:

	/** IModuleInterface implementation */
	virtual void StartupModule() override;
	virtual void ShutdownModule() override;
	
	/** This function will be bound to Command (by default it will bring up plugin window) */
	void PluginButtonClicked();
	
	void TreeView_OnGetChildren(TSharedPtr<FScriptPathItem> Item, TArray<TSharedPtr<FScriptPathItem>>& OutChildren);
	
	TSharedRef<class ITableRow> TreeView_OnGenerateRow(TSharedPtr<FScriptPathItem> Item,
		const TSharedRef< class STableViewBase >& OwningWidget);
private:

	void RegisterMenus();

	TSharedRef<class SDockTab> OnSpawnPluginTab(const class FSpawnTabArgs& SpawnTabArgs);

	/**
	 * 读取 Json 配置文件
	 */
	void ReadConfigJson();

	/**
	 * 获取对应的路径别名
	 * @param inPath 路径
	 * @param outAlias 别名
	 */
	void GetPathAlias(const FString& inPath, FString& outAlias);
	
	/**
	 * 搜索脚本路径
	 */
	void SearchScriptPath();

	/**
	 * 递归搜索文件 "main.py"
	 * @param rootPath 
	 */
	bool SearchScriptPathRecursive(TSharedPtr<FScriptPathItem>& inRoot);

	/**
	 * 创建父层级控件
	 * @param Item 
	 * @return 
	 */
	TSharedRef<SWidget> CreateTreeItem_Folder(const TSharedPtr<FScriptPathItem>& Item);

	/**
	 * 创建文件按钮
	 * @param Item 
	 * @return 
	 */
	TSharedRef<SWidget> CreateTreeItem_File(const TSharedPtr<FScriptPathItem>& Item);
private:
	TSharedPtr<class FUICommandList> PluginCommands;

	TArray<TSharedPtr<FScriptPathItem>> mRootModules;

	// Json
	TSharedPtr<FJsonObject> mCfgJsonRoot;
	
	// Style
	FTableViewStyle mTreeStyle;
	TSharedPtr<FSlateBrush> mTreeBrush;
	FTableRowStyle mRowStyle;
	// Tree Row Style Brush
	FSlateColorBrush mColorBrush_Normal{FLinearColor{0.007499f, 0.007499f, 0.007499f, 1.f}};
	FSlateColorBrush mColorBrush_Hover{FLinearColor{0.175069f, 0.6f, 0.f, 1.f}};
	FSlateColorBrush mColorBrush_Active{FLinearColor{1.f, 0.502887f, 0.f, 1.f}};
	FSlateColorBrush mColorBrush_ActiveHover{FLinearColor{0.175069f, 0.6f, 0.f, 1.f}};
	FSlateColorBrush mColorBrush_ActiveHighLighted{FLinearColor{0.027321f, 0.027321f, 0.027321f, 1.f}};
};

